<?php
/**
 * 系统路由器实现，
 * 核心router组件，提供url提取功能，与用户态的router组件通过url交互
 * @author yusaint
 * @since 2014-3-9
 * @project Pfinal
 */
class PfinalRouter{
	
	protected $pfinalConfig;
	
	public function __construct(PfinalConfig $pfinalConfig){
		$this->pfinalConfig = $pfinalConfig;	
	}
	
	/**
	 * 根据路由规则，提取注册的routers，来提供路由功能
	 */
	public function dispatch(){
		$routerConfig = $this->pfinalConfig->getRoute();
		$registedRouters = $routerConfig->getRouteStack();
		foreach ($registedRouters as $router){
			//切入点,other plugin 怎么切入
			//Pfinal_AOP_Handler->invoke($router,$url,$kernelConfig)
			$routed = $router->route($this->getUrl(),$this->pfinalConfig);
			if ($routed)
				return $router;				
		}		
		return end($registedRouters);
	}

	public function getUrl(){
		$devMode = $this->pfinalConfig->getConstant()->getDevMode();
		switch ($devMode) {
			case Pfinal_Config_Constant::MODE_DEV:
			case Pfinal_Config_Constant::MODE_CLI:
				return $this->getCliUrl();
				break;
			case Pfinal_Config_Constant::MODE_PRODUCT:
				$routeConfig = $this->pfinalConfig->getRoute();
				$uri = $routeConfig->getUri();
				if (!empty($uri)) {
					return $routeConfig->getUri();
				}
				return $this->getWebServerUrl();
			default:
				# code...
				break;
		}
	}

	protected function getCliUrl(){
		$params = $_SERVER['argv'];
		if (isset($params[1])) {
			return $params[1];
		}
		return '';
	}
	
	/**
	 * 首先查找INFO_PATH
	 */
	protected function getWebServerUrl(){
		$uri = '';
		if (isset($_SERVER['PATH_INFO'])&&!empty($_SERVER['PATH_INFO'])){
			$uri.= $_SERVER['PATH_INFO'];
		}
		$uri = trim($uri,'/');
		if (empty($uri)){
			$uri .= 'index/index';
		}
		return trim($uri,'/');
	}
} 
?>